<?php
App::uses('Crud', 'Model');
App::uses('User', 'Model');
App::uses('TransportRequest', 'Model');

class TransportUser extends Crud
{
    const STATUS_ENABLED = 1;
    const STATUS_DISABLED = 0;

    public function getEnabledByRequestId($requestId) {
        $filters = array(
            'fields' => array(
                'u.full_name as user',
                'TransportUser.line as line',
                'TransportUser.street as street',
                'TransportUser.number as number',
                'TransportUser.colony as colony',
                'TransportUser.between_streets as btwStreets',
                'TransportUser.signature as sing'
            ),
            'joins' => array(
                array(
                    'table' => 'us3rs_r4gg14n4',
                    'alias' => 'u',
                    'type' => 'inner',
                    'conditions' => array(
                        'TransportUser.user_id = u.id',
                        'u.status' => User::STATUS_ENABLED
                    )
                )
            ),
            'conditions' => array(
                'TransportUser.transport_request_id' => $requestId,
                'TransportUser.status' => self::STATUS_ENABLED
            )
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    public function destroyRequest($scheduleId, $userId) {
        $filters = array(
            'fields' => array(
                'TransportUser.id'
            ),
            'joins' => array(
                array(
                    'table' => 'transport_requests',
                    'alias' => 'tr',
                    'type' => 'inner',
                    'conditions' => array(
                        'tr.id = TransportUser.transport_request_id',
                        'tr.schedule_id' => $scheduleId,
                        'tr.status' => TransportRequest::STATUS_ENABLED
                    )
                )
            ),
            'conditions' => array(
                'TransportUser.user_id' => $userId,
                'TransportUser.status' => self::STATUS_ENABLED
            )
        );
        $records = $this->find('first', $filters);
        $tu = array(
            'id' => $records['TransportUser']['id'],
            'status' => self::STATUS_DISABLED
        );
        $this->save($tu);
    }
}